package edu.njust.controller;

import edu.njust.Service.user.UserService;
import edu.njust.controller.depcontroller.Code;
import edu.njust.controller.depcontroller.Result;
import edu.njust.domain.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/UserController")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}/{password}")
    public Result getById(@PathVariable int id, @PathVariable String password) {
        User user = userService.getUserByID(id, password);
        Integer code = user != null ? Code.GET_OK : Code.GET_ERR;
        String msg = user != null ? "" : "数据查询失败，请重试！";
        return new Result(code,user,msg);

    }

    @GetMapping
    public Result getUsers() {
        List<User> users = userService.getUsers();
        Integer code = users != null ? Code.GET_OK : Code.GET_ERR;
        String msg = users != null ? "" : "数据查询失败，请重试！";
        return new Result(code,users, msg);
    }

    @PostMapping
    public Result addUser(@RequestBody User user) {
        System.out.println(user);
        boolean flag = userService.addUser(user);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
    }


    @PutMapping
    public Result updateUserPwd(@RequestBody User user) {
        boolean flag = userService.updateUserPwd(user);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }

    @PutMapping("/other")
    public Result updateUserOther(@RequestBody User user) {
        boolean flag = userService.updateUserOther(user);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }


    @DeleteMapping()
    public Result deleteUser(@RequestBody User user) {
        boolean flag = userService.deleteUser(user.getCM_ID(),user.getCM_PWD(),
                user.getModifiedUser(),user.getModifiedTime());
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }

}
